﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace FreedomX2.Core.Log
{
    public static class ExceptionEx
    {
        public static Exception Exception = new Exception("日志自动方法");
        public static void l(this string message)
        {
            l(Exception, message);
        }
        public static void e(this string message)
        {
            e(Exception, message);
        }
        public static void l(this System.Exception e, string message)
        {
            var file = GetFile();
            file.WriteLine("ESMSG@"+Envior.Ment.MARKSTRING+"@" + DateTime.Now.ToString("HH:mm:ss") + "  " + message);
            CloseFile(file);
        }
        public static Exception e(this System.Exception ex)
        {
            if (ex.Message == "日志自动方法") return null;
            ex.e(ex.Message + "\t{esaddressbegin}" + ex.StackTrace + "{esaddressend}");
            return ex;
        }
        public static Exception e(this System.Exception ex, string error)
        {
            if (ex.Message == "日志自动方法") return null;
            var file = GetFile();
            file.WriteLine("ESERR@" + Envior.Ment.MARKSTRING + "@" + DateTime.Now.ToString("HH:mm:ss") + "  " + error);
            CloseFile(file);
            return ex;
        }
        private static void CloseFile(StreamWriter sw)
        {
            sw.Close();
            sw = null;
        }
        private static StreamWriter GetFile()
        {
            string strPath = AppDomain.CurrentDomain.BaseDirectory + "\\log\\";
            if (!Directory.Exists(strPath)) Directory.CreateDirectory(strPath);
            string strfilename = DateTime.Now.ToString("yyyyMMdd") + ".ESLog";
            FileStream fs = new FileStream(strPath + strfilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            fs.Position = fs.Length;
            return new StreamWriter(fs);

        }
    }
}
